package com.lianxi.util;



import okhttp3.*;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.TimeUnit;


/**
 * Created by Administrator on 2017/4/5.
 */

public class OkHttpUtils {

    private static final Logger logger = LoggerFactory.getLogger(OkHttpUtils.class);

    private static OkHttpClient mOkHttpClient;

    //2.暴露出一个方法，返回当前类的对象
    private static OkHttpUtils mInstance;
    public static OkHttpUtils newInstance() {
        if (mInstance == null) {
            //实例化对象
            //加上一个同步锁，只能有一个执行路径进入
            synchronized (OkHttpUtils.class) {
                if (mInstance == null) {
                    mInstance = new OkHttpUtils();
                }
                if (mOkHttpClient == null) {
                    mOkHttpClient = new OkHttpClient();
                }
            }
        }
        return mInstance;
    }

    public static OkHttpUtils newTimeInstance(int seconds){
        if (mInstance==null){
            synchronized (OkHttpUtils.class) {
                if (mInstance == null) {
                    mInstance = new OkHttpUtils();
                }
                if (mOkHttpClient == null) {
                    mOkHttpClient = new OkHttpClient.Builder().readTimeout(seconds, TimeUnit.SECONDS).build();
                }
            }
        }
        return mInstance;
    }




//            //关闭防止内存泄漏
//            if(response.body()!=null){
//                response.body().close();
//  }


    /**
     * Get请求
     *
     * @param url
     */
    public Response doGet(String url) {
        Response response = null;
        Request request = new Request.Builder()
                .url(url)
                .build();
        try {
            response =mOkHttpClient.newCall(request).execute();
        } catch (Exception e) {
            logger.info(">>>>>>>>>>>>>>>>>>okhttp get 异常 {},url is {}",e.getMessage(),url);
            return null;
//            e.printStackTrace();
        }
        return response;
    }
    public Response doGet(String url, Map<String, String> header) {
        Response response = null;
        Request request = new Request.Builder()
                .headers(setHeaders(header))
                .url(url)
                .build();
        try {
            response = mOkHttpClient.newCall(request).execute();
        } catch (IOException e) {
            logger.info(">>>>>>>>>>>>okhttp get请求异常{},url {} ",e.getMessage(),url);
            e.printStackTrace();
        }
        return response;
    }

    /**
     * 添加header
     * @param header header
     */
    private Headers setHeaders(Map<String, String> header) {
        Headers headers;
        Headers.Builder headersBuilder = new Headers.Builder();
        if (header != null) {
            Iterator<String> iterator = header.keySet().iterator();
            String key;
            while (iterator.hasNext()) {
                key = iterator.next();
                headersBuilder.add(key, header.get(key));
            }
        }
        headers = headersBuilder.build();
        return headers;
    }


    /**
     * Post请求发送键值对数据
     *
     * @param
     * @param url
     * @param mapParams
     */
    public  Response doPost(String url, Map<String, String> mapParams) {
        Response response = null;
        FormBody.Builder builder = new FormBody.Builder();
        for (String key : mapParams.keySet()) {
            builder.add(key, mapParams.get(key));
        }
        Request request = new Request.Builder()
                .url(url)
                .post(builder.build())
                .build();
        try {
            response =mOkHttpClient.newCall(request).execute();
        } catch (Exception e) {
            logger.info(">>>>>>>>okhttp post 异常 {},url is {}",e.getMessage(),url);
            return  null;
//            e.printStackTrace();
        }
        return response;
    }


    /**
     * Post请求发送键值对数据
     *
     * @param
     * @param url
     * @param mapParams
     */
    public  Response doPostAndHear(String url, Map<String, String> mapParams,String cookie) {
        Response response = null;
        FormBody.Builder builder = new FormBody.Builder();
        for (String key : mapParams.keySet()) {
            builder.add(key, mapParams.get(key));
        }
        Request request = new Request.Builder()
                .header("Cookie",cookie)
                .url(url)
                .post(builder.build())
                .build();
        try {
            response =mOkHttpClient.newCall(request).execute();
        } catch (Exception e) {
            logger.info(">>>>>>>>okhttp post 异常 {},url is {}",e.getMessage(),url);
            return  null;
//            e.printStackTrace();
        }
        return response;
    }



    /**
     * Post请求发送键值对数据
     *
     * @param
     * @param url
     * @param mapParams
     */
    public  Response doPostHeiMa(String url, Map<String, String> mapParams,String token) {
        Response response = null;
        FormBody.Builder builder = new FormBody.Builder();
        for (String key : mapParams.keySet()) {
            builder.add(key, mapParams.get(key));
        }
        Request request = new Request.Builder()
                .url(url).addHeader("token",token)
                .post(builder.build())
                .build();
        try {
            response =mOkHttpClient.newCall(request).execute();
        } catch (Exception e) {
            logger.info(">>>>>>>>okhttp post 异常 {},url {}",e.getMessage(),url);
            return  null;
//            e.printStackTrace();
        }
        return response;
    }

    /**
     * Post请求发送键值对数据
     *
     * @param
     * @param url
     * @param mapParams
     */
    public  Response doPost(String url, Map<String, Object> mapParams,String token) {
        Response response = null;
        FormBody.Builder builder = new FormBody.Builder();
        for (Object key : mapParams.keySet()) {
            builder.add(key.toString(), mapParams.get(key).toString());
        }
        Request request = new Request.Builder()
                .url(url).addHeader("token",token)
                .post(builder.build())
                .build();
        try {
            response =mOkHttpClient.newCall(request).execute();
        } catch (Exception e) {
            logger.info(">>>>>>>>okhttp post 异常 {},url {}",e.getMessage(),url);
            return  null;
//            e.printStackTrace();
        }
        return response;
    }
    /**
     * Post请求发送键值对数据
     *
     * @param
     * @param url
     * @param mapParams
     */
    public  Response doPostHeader(String url, Map<String, String> mapParams,String headerName,String headerValue) {
        Response response = null;
        RequestBody body = FormBody.create(MediaType.parse(headerValue), "");
        Request request = new Request.Builder()
                .addHeader(headerName,headerValue)
                .url(url)
                .post(body)
                .build();
        try {
            response =mOkHttpClient.newCall(request).execute();
        } catch (Exception e) {
            logger.info(">>>>>>>>okhttp post 异常 {},url {}",e.getMessage(),url);
            return  null;
//            e.printStackTrace();
        }
        return response;
    }

    public Response doPostHeader(String url, Map<String, String> mapParams, Headers headers) {
        Response response = null;
        FormBody.Builder builder = new FormBody.Builder();
        for (String key : mapParams.keySet()) {
            builder.add(key, mapParams.get(key));
        }
        Request request = new Request.Builder().headers(headers)
                .url(url)
                .post(builder.build())
                .build();
        try {
            response = mOkHttpClient.newCall(request).execute();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return response;
    }

    /**
     * Post请求发送键值对数据
     *
     * @param
     * @param url
     * @param mapParams
     */
    public  Response doPostHeaderAndParams(String url, Map<String, Object> mapParams,String headerName,String headerValue) {
        Response response = null;
        FormBody.Builder builder = new FormBody.Builder();
        for (Object key : mapParams.keySet()) {
            builder.add(key.toString(), mapParams.get(key).toString());
        }
        Request request = new Request.Builder()
                .addHeader(headerName,headerValue)
                .url(url)
                .post(builder.build())
                .build();
        try {
            response =mOkHttpClient.newCall(request).execute();
        } catch (Exception e) {
            logger.info(">>>>>>>>okhttp post 异常 {},url {}",e.getMessage(),url);
            return  null;
//            e.printStackTrace();
        }
        return response;
    }

    /**
     * Post请求发送键值对数据
     *融云使用
     * @param
     * @param url
     * @param jsonParams
     */
    public  Response doDeleteRCloud(String url, String jsonParams,String uid,String nonce,String timestamp,String sign) {
        Response response = null;
        RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8")
                , jsonParams);
        Request request = new Request.Builder().addHeader("uid",uid).addHeader("nonce",nonce).addHeader("timestamp",timestamp).addHeader("sign",sign)
                .url(url)
                .delete(body)
                .build();
        try {
            response = mOkHttpClient.newCall(request).execute();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return response;
    }
    /**
     * Post请求发送键值对数据
     *融云使用
     * @param
     * @param url
     * @param jsonParams
     */
    public  Response doPutRCloud(String url, String jsonParams,String uid,String nonce,String timestamp,String sign) {
        Response response = null;
        RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8")
                , jsonParams);
        Request request = new Request.Builder().addHeader("uid",uid).addHeader("nonce",nonce).addHeader("timestamp",timestamp).addHeader("sign",sign)
                .url(url)
                .put(body)
                .build();
        try {
            response = mOkHttpClient.newCall(request).execute();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return response;
    }
    /**
     * Post请求发送键值对数据
     *融云使用
     * @param
     * @param url
     * @param jsonParams
     */
    public  Response doPostRCloud(String url, String jsonParams,String uid,String nonce,String timestamp,String sign) {
        Response response = null;
        RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8")
                , jsonParams);
        Request request = new Request.Builder().addHeader("uid",uid).addHeader("nonce",nonce).addHeader("timestamp",timestamp).addHeader("sign",sign)
                .url(url)
                .post(body)
                .build();
        try {
            response = mOkHttpClient.newCall(request).execute();
        } catch (IOException e) {

            e.printStackTrace();
        }
        return response;
    }
    /**
     * Post请求发送键值对数据
     *融云使用
     * @param
     * @param url
     * @param jsonParams
     */
    public  Response doPostRCloudRCX(String url, String jsonParams,String app_key,String nonce,String timestamp,String sign,String mediaType) {
        Response response = null;
        RequestBody body = RequestBody.create(MediaType.parse(mediaType)
                , jsonParams);
        Request request = new Request.Builder().addHeader("App-key",app_key).addHeader("Nonce",nonce).addHeader("Timestamp",timestamp).
                addHeader("Signature",sign)
                .url(url)
                .post(body)
                .build();
        try {
            response = mOkHttpClient.newCall(request).execute();
        } catch (IOException e) {

            e.printStackTrace();
        }
        return response;
    }
    /**
     * Post请求发送键值对数据
     *融云使用
     * @param
     * @param url
     */
    public  Response doGetRCloud(String url,String uid,String nonce,String timestamp,String sign) {
        Response response = null;
        Request request = new Request.Builder().addHeader("uid",uid).addHeader("nonce",nonce).addHeader("timestamp",timestamp).addHeader("sign",sign)
                .url(url)
                .get()
                .build();
        try {
            response = mOkHttpClient.newCall(request).execute();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return response;
    }
    /**
     * Post请求发送键值对数据
     *
     * @param
     * @param url
     * @param mapParams
     */
    public  Response doPostSystem(String url, Map<String, String> mapParams,String head) {
        Response response = null;
        FormBody.Builder builder = new FormBody.Builder();
        for (String key : mapParams.keySet()) {
            if (StringUtils.isNotBlank(mapParams.get(key))){
                builder.add(key, mapParams.get(key));
            }
        }
        Request request = new Request.Builder().addHeader("yanzheng",head)
                .url(url)
                .post(builder.build())
                .build();
        try {
            response =mOkHttpClient.newCall(request).execute();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return response;
    }
    /**
     * Post请求发送键值对数据
     *
     * @param
     * @param url
     * @param mapParams
     */
    public  Response doPostCMS(String url, Map<String, String> mapParams,String token) {
        Response response = null;
        FormBody.Builder builder = new FormBody.Builder();
        if (mapParams!=null){
            for (String key : mapParams.keySet()) {
                if (StringUtils.isNotBlank(mapParams.get(key))){
                    builder.add(key, mapParams.get(key));
                }
            }
        }

        Request request = new Request.Builder().addHeader("token",token)
                .url(url)
                .post(builder.build())
                .build();
        try {
            response =mOkHttpClient.newCall(request).execute();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return response;
    }
    /**
     * Post请求发送键值对数据
     *
     * @param
     * @param url
     * @param mapParams
     */
    public  Response doPostCMS(String url, Map<String, String> mapParams,String... token) {
        Response response = null;
        FormBody.Builder builder = new FormBody.Builder();
        if (mapParams!=null){
            for (String key : mapParams.keySet()) {
                if (StringUtils.isNotBlank(mapParams.get(key))){
                    builder.add(key, mapParams.get(key));
                }
            }
        }

        Request request = new Request.Builder().addHeader("token",token[0]).addHeader("phone",token[1])
                .url(url)
                .post(builder.build())
                .build();
        try {
            response =mOkHttpClient.newCall(request).execute();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return response;
    }

    /**
     * Post请求发送键值对数据
     *
     * @param
     * @param url
     * @param jsonParams
     */
    public  Response doPostDingNews(String url, String jsonParams,String... token) {
        Response response = null;
        RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), jsonParams);
        Request request = new Request.Builder().addHeader("token",token[0]).addHeader("timestamp",token[1]).addHeader("tenantId",token[2])
                .url(url)
                .post(body)
                .build();
        try {
            response =mOkHttpClient.newCall(request).execute();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return response;
    }


    /**
     * Post请求发送JSON数据
     *  @param url
     * @param jsonParams
     */
    public Response doPost(String url, String jsonParams) {
        Response response = null;
        RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8")
                , jsonParams);
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();
        try {
            response = mOkHttpClient.newCall(request).execute();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return response;
    }


    public interface HttpCallBack {
        void onError(Response response, IOException e);

        void onSuccess(Response response, String result);
    }

    public void asyncGet(String url, final HttpCallBack httpCallBack) {
        final Request request = new Request.Builder().url(url).build();
        mOkHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                final String result = response.body().string();
                if (httpCallBack != null) {
                    httpCallBack.onSuccess(response, result);
                }
            }
        });
    }


    public void asyncPost(String url, RequestBody formBody, final HttpCallBack httpCallBack) {
        final Request request = new Request.Builder().url(url).post(formBody).build();
        mOkHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                logger.info(">>>>>>>>>>>>>>>asyncPost failure");
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                final String result = response.body().string();
                if (httpCallBack != null) {
                    httpCallBack.onSuccess(response, result);
                }
            }
        });
        try {
            Thread.sleep(300);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    /**
     * 异步处理指令（暂时只是指令）
     * @param url
     * @param formBody
     * @param httpCallBack
     */
    public void asyncPostnew(String url, RequestBody formBody, final HttpCallBack httpCallBack) {
        final Request request = new Request.Builder().url(url).post(formBody).build();
        mOkHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                logger.info(">>>>>>>>>>>>>>>asyncPostNews fail");
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                final String result = response.body().string();
                if (httpCallBack != null) {
                    httpCallBack.onSuccess(response, result);
                }
            }
        });
    }


    public void asyncShieldBack(String url,RequestBody formBody){
        this.asyncPostnew(url, formBody, new HttpCallBack() {
            @Override
            public void onError(Response response, IOException e) {
                logger.info(">>>>>>asyncShieldBack response {},msg {}",response.body().toString(),e.getMessage());
            }

            @Override
            public void onSuccess(Response response, String result) {
               logger.info(">>>>>>>>>>asyncShieldBack response {},result {}",response.toString(),result);
            }
        });
    }
/*    //七牛鉴黄的方法（备用）
    private final Client client = new Client();
    public void post(Auth auth, String body) throws QiniuException {
        String url = "http://ai.qiniuapi.com/v3/image/censor";
        byte[] b = body.getBytes();
        StringMap headers = auth.authorizationV2(url, "POST", b, Client.JsonMime);
        com.qiniu.http.Response r = client.post(url, b, headers, Client.JsonMime);
        System.out.println(r.bodyString());
    }*/
}
